package com.ljm.shirojwt.shiro;


import com.ljm.shirojwt.entity.User;
import com.ljm.shirojwt.service.UserService;
import com.ljm.shirojwt.service.serviceImpl.UserServiceImpl;
import com.ljm.shirojwt.utils.ApplicationContextUtils;
import com.ljm.shirojwt.utils.JwtUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class TestRealm extends AuthorizingRealm {

    //根据工厂获取userService
//    UserService userService = (UserService) ApplicationContextUtils.getBean("userService");

    @Autowired
    UserServiceImpl userService;
    /**
     * 必须重写
     *
     * @param token
     * @return
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        String token = (String) auth.getCredentials();
        //为什么是token而不是身份信息？
        //因为我们不是调用subject.login()方法，而是自定义验证方法
        //  String principal = (String) token.getPrincipal();

        String username = JwtUtils.getUsername(token);
        if (token == null) {
            throw new AuthenticationException("token is null");
        }
        User userDB = userService.getByUsername(username);
        if (userDB == null) {
            throw new AuthenticationException("User didn't existed!");
        }
        if (!JwtUtils.verify(token, username, userDB.getPassword())) {
            throw new AuthenticationException("Username or password error");
        }
        return new SimpleAuthenticationInfo(token, token, this.getName());
    }
}
